local function GetStringsTable()
    return TUNING.NPC_CHAT_TABLE[ type(TUNING.__NPC_LANGUAGE)=="function" and TUNING.__NPC_LANGUAGE() or TUNING.__NPC_LANGUAGE ] ["npc_event_item_buyer"] or {}
end

local function check_is_first_gift(player,str)
    if TheWorld.npc_everything_data:Get(player.userid..str) ~= true then
        TheWorld.npc_everything_data:Set(player.userid..str,true)
        return true
    end
    return false
end

local function gift_2_players(inst)
    local pt = Vector3(inst.Transform:GetWorldPosition())
    local players = TheSim:FindEntities(pt.x, 0, pt.z, 5.5, {"player"}, {"playerghost"}, nil)
    local first_gift_say_flag = false
    if #players > 0 then
        for k, theplayer in pairs(players) do
            if theplayer and theplayer.userid and theplayer.components.playercontroller then
                --------------------------------------------------------------------------------------------------------
                local the_gifts_list = {}
                if check_is_first_gift(theplayer,"__trade_station_kit_gift") then
                    table.insert(the_gifts_list,{"npc_item_tree_trade_station_kit",1})
                    first_gift_say_flag = true
                end
                --------------------------------------------------------------------------------------------------------
                if check_is_first_gift(theplayer,".pigman_first_gift.npc_item_cards_experience_pack") then
                    table.insert(the_gifts_list,{"npc_item_cards_experience_pack",1})
                    first_gift_say_flag = true
                end
                --------------------------------------------------------------------------------------------------------   
                if check_is_first_gift(theplayer,".pigman_first_gift.npc_item_rainbow_horn") then
                    table.insert(the_gifts_list,{"npc_item_rainbow_horn",1,function(theHorn)
                        theHorn.components.finiteuses.current = 1
                    end})
                    first_gift_say_flag = true
                end
                --------------------------------------------------------------------------------------------------------     
                --------------------------------------------------------------------------------------------------------     
                ---- Spawn Gift Pack and Give Player
                if #the_gifts_list ~= 0 then
                    theplayer:DoTaskInTime(1.5,function()
                        theplayer:SpawnChild("npc_fx_knowledge_flash"):PushEvent("Set",{pt = Vector3(0,1,0),color = Vector3(0,255,0)}) 
                        local pack_cmd = {
                            Items = {
                                    -- {"log",num},
                                    -- {"goldnugget",20}
                            },
                            Name = GetStringsTable()["gift_pack.name"],
                            Inspect_str = GetStringsTable()["gift_pack.inspect_str"],
                            Skin = math.clamp(#the_gifts_list,1,6),   -- 1~6
                        }
                        pack_cmd.Items = the_gifts_list
                        local theGift = SpawnPrefab("npc_gift_pack")
                        theGift:PushEvent("ADD",pack_cmd)
                        theplayer.components.inventory:GiveItem(theGift)
                    end)
                    
                end
                --------------------------------------------------------------------------------------------------------                    
            end
        end

        if first_gift_say_flag then
            inst.npc_base_lib:Say(GetStringsTable().first_gift)
        end

    end

end
local function recycle_point_exchange(inst)
    local point = TheWorld.npc_everything_data:Add("recycle_point",0)
    if point > 1 then
        local player = inst:GetNearestPlayer(true)
        if player and player.components.playercontroller and player.npc_base_lib then
            local ret_point = point%0.1
            local gold_num = math.ceil(point - ret_point)
            if TUNING.NPC_CONFIG.REWARDS_LESS == false then
                gold_num = gold_num *2
            end
            player.npc_base_lib:GiveItemByName("goldnugget",gold_num)
            TheWorld.npc_everything_data:Set("recycle_point",ret_point)
            TheWorld.npc_everything_data:Set("recycle_point_announce",false)
            inst.npc_base_lib:Say(GetStringsTable().recycle_exchange)
        end
    end
end
local function prototyper_onturnon(inst)
    if inst.awake_flag ~= true then
        inst.awake_flag = true
        inst.AnimState:PlayAnimation("sleep_pst")
        inst.AnimState:PushAnimation("idle",true)
        inst.npc_base_lib:Say("    ")
        gift_2_players(inst)
        inst:DoTaskInTime(2,recycle_point_exchange)
    end
end
local function prototyper_onturnoff(inst)
    if inst.awake_flag == true then
        inst.awake_flag = false
        inst.AnimState:PlayAnimation("sleep_pre")
        inst.AnimState:PushAnimation("sleep_loop",true)
    end
end

local function prototyper_onactivate(inst, doer, recipe)
	-- if recipe ~= nil then
	-- 	if recipe.name == "carnival_plaza_kit" then
	-- 		if not inst.hassold_plaza then
	-- 			inst.hassold_plaza = true
	-- 			-- AddPlazaWares(inst)
	-- 			-- DoPrototyperChatter(inst)
	-- 		end
	-- 	elseif recipe.name == "carnival_prizebooth_kit" then
	-- 		inst.hassold_prizebooth = true
	-- 	end
	-- end
    -- if doer and doer.userid then
        
    -- end
end

local function fn()
    local inst = CreateEntity()
    TheSim:LoadPrefabs({ "quagmire_swampigelder" })

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddMiniMapEntity()
    inst.entity:AddNetwork()

    inst.entity:AddDynamicShadow()
    -- inst.entity:AddLight()

    MakeObstaclePhysics(inst, 1, .5)

    inst.MiniMapEntity:SetIcon("pigking.png")
    inst.MiniMapEntity:SetPriority(1)

    --prototyper (from prototyper component) added to pristine state for optimization
    inst:AddTag("prototyper")

    inst.AnimState:SetBank("quagmire_elderswampig")
    inst.AnimState:SetBuild("quagmire_elderswampig")
    inst.AnimState:PlayAnimation("sleep_loop", true)
    inst.AnimState:SetScale(0.6,0.6,0.6)

    inst:AddTag("character")
    inst:AddTag("monster_npc_pigman_intermediary_businessman")
    --Sneak these into pristine state for optimization
    inst:AddComponent("talker")
    inst.components.talker.fontsize = 35
    inst.components.talker.font = TALKINGFONT
    inst.components.talker.colour = Vector3(165/255, 180/255, 200/255)
    inst.components.talker.offset = Vector3(0, -650, 0)
    inst.components.talker:MakeChatter()


    inst.talk_sound = "dontstarve/quagmire/creature/swamppig_elder/talk"

    inst.entity:SetPristine()


    if not TheWorld.ismastersim then    --------------------------------------------------
        return inst
    end
    inst:AddComponent("npc_base_lib")
    inst:AddComponent("npc_everything_data")

    inst:AddComponent("inspectable") --可检查组件
    inst:AddComponent("named") --名字组件
    inst.components.named:SetName(GetStringsTable().pigman_name)
    STRINGS.CHARACTERS.GENERIC.DESCRIBE[string.upper("monster_npc_pigman_intermediary_businessman")] = GetStringsTable().inspect_str_pigman  --人物检查的描述


    inst:AddComponent("prototyper") ---- 靠近触发科技的交易系统
    -- inst.components.prototyper.onturnon = prototyper_onturnon
    -- inst.components.prototyper.onturnoff = prototyper_onturnoff
    -- inst.components.prototyper.onactivate = prototyper_onactivate
    inst.components.prototyper.trees = TUNING.PROTOTYPER_TREES[string.upper("intermediary_pigman_shop")]

    inst:DoTaskInTime(0,function()
        if inst.Ready ~= true then
            inst:Remove()
            return
        end
    end)

    inst:DoPeriodicTask(2,function()
        if inst:IsNearPlayer(6,true) then
            prototyper_onturnon(inst)
        else
            prototyper_onturnoff(inst)
        end
    end)
   
    return inst
end

return Prefab("monster_npc_pigman_intermediary_businessman", fn)
